//
//  File.swift
//  
//
//  Created by ellzu gu on 2021/9/3.
//

import Foundation

class FilePacket {
    var file: FileHandle
    var dataOffset: UInt64 = 0
    var header: PacketHeader
    public init(_ file: FileHandle) {
        self.file = file
        self.header = PacketHeader.header(0x01)!
        self.header.dataCount = self.file.seekToEndOfFile()
        self.header.type = .File
    }
    
}

extension FilePacket: InputPacket {
    var inputHeader: PacketHeader { self.header }
    func readData(_ buf: UnsafeMutableRawPointer, bufCount: UInt64) -> Int {
        let avaliableCount = min(bufCount, self.header.dataCount - self.dataOffset)
        file.seek(toFileOffset: UInt64(self.dataOffset))
        let data = file.readData(ofLength: Int(avaliableCount))
        data.copyBytes(to: buf.assumingMemoryBound(to: UInt8.self), count: data.count)
        self.dataOffset += UInt64(data.count)
        return data.count
    }
}
